package com.ajieee.merge.runner.finance;

import cn.idev.excel.FastExcel;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.read.listener.ReadListener;
import com.ajieee.merge.entity.finance.po.EtfQuotePO;
import com.ajieee.merge.enums.finance.EtlType;
import com.ajieee.merge.mapper.EtfQuoteMapper;
import com.ajieee.merge.runner.finance.dto.EtfQuoteExcelModel;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.client.RestClient;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ajieee
 * @date 2025-10-04
 */
@Order(EtlOrder.QUOTE_ORDER)
@Component
@RequiredArgsConstructor
public class SzseEtfQuoteEtl extends AbstractEtl {

	private final RestClient restClient;

	private final EtfQuoteMapper etfQuoteMapper;

	@Override
	public void doExecute() {
		String uriString = UriComponentsBuilder.fromUriString("https://www.szse.cn/api/report/ShowReport")
				.queryParam("SHOWTYPE", "xlsx")
				.queryParam("CATALOGID", "1815_stock_snapshot")
				.queryParam("TABKEY", "tab2")
				.queryParam("txtBeginDate", getTradeDate())
				.queryParam("txtEndDate", getTradeDate())
				.build().encode().toUriString();
		byte[] respBytes = restClient.get()
				.uri(uriString)
				.retrieve()
				.body(byte[].class);
		Assert.notNull(respBytes, "请求深圳ETF行情错误");

		List<EtfQuotePO> pos = new ArrayList<>();
		FastExcel.read(new ByteArrayInputStream(respBytes), EtfQuoteExcelModel.class, new ReadListener<EtfQuoteExcelModel>() {
			boolean first = true;

			@Override
			public void invoke(EtfQuoteExcelModel data, AnalysisContext context) {
				if (first) {
					data.validate();
					first = false;
				}

				EtfQuotePO po = new EtfQuotePO();
				BeanUtils.copyProperties(data, po);
				po.setDataDate(getTradeDate());
				pos.add(po);
			}

			@Override
			public void doAfterAllAnalysed(AnalysisContext context) {
				if (!pos.isEmpty()) {
					etfQuoteMapper.insert(pos);
				}
			}
		}).doReadAll();
	}

	@Override
	public EtlType getType() {
		return EtlType.SZSE_ETF_QUOTE;
	}
}
